import { getTimestamp } from '@/utils/date';
import { formatFiles } from '@/utils/format';
import { isEmptyArray } from '@/utils/index';
import dayjs from 'dayjs';
import type { ConfigProps } from './type.js';

// 格式化表单数据（提交用）
export const formatSubmitData = (
  configList: ConfigProps[],
  data: Record<string, any>,
) => {
  if (!data) return {};
  const result = { ...data };
  configList.forEach(({ type, dataIndex, fieldNames }) => {
    const value = result[dataIndex];
    if (value === null) {
      delete result[dataIndex];
      return;
    }
    switch (type) {
      case 'input':
      case 'textarea':
        result[dataIndex] = typeof value === 'string' ? value.trim() : value;
        break;
      case 'date':
        result[dataIndex] = getTimestamp(value);
        break;
      case 'dateRange':
        if (!isEmptyArray(value) && fieldNames?.length === 2) {
          result[fieldNames[0]] = getTimestamp(value[0]);
          result[fieldNames[1]] = getTimestamp(value[1]);
          delete result[dataIndex];
        }
        break;
      default:
        break;
    }
  });
  return result;
};

// 格式化表单数据（回显用）
export const formatRenderData = (
  configList: ConfigProps[],
  data: Record<string, any>,
) => {
  if (!data) return {};
  const result = { ...data };
  configList.forEach(({ type, dataIndex, fieldNames }) => {
    const value = result[dataIndex];
    switch (type) {
      case 'date':
        result[dataIndex] = value ? dayjs(value) : undefined;
        break;
      case 'dateRange':
        if (!isEmptyArray(value)) {
          result[dataIndex] = value.map((item: number) => dayjs(item));
        } else if (fieldNames?.length === 2) {
          result[dataIndex] = [
            dayjs(result[fieldNames[0]]),
            dayjs(result[fieldNames[1]]),
          ];
        }
        break;
      case 'upload':
        result[dataIndex] = formatFiles(value);
      default:
        break;
    }
  });
  return result;
};
